//
//  CourseDetailViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/9/21.
//

import UIKit
import SwiftyJSON
import Toast_Swift
import Alamofire
import AlamofireImage
import EFQRCode

class CourseDetailViewController: BaseViewController {

    var courseId = ""
    var courseData = JSON.init(parseJSON: "{}")
    var courseWareTitle = ""
    
    @IBOutlet weak var courseCover: UIButton!
    @IBOutlet weak var courseTitle: UILabel!
    @IBOutlet weak var courseDesc: UILabel!
    @IBOutlet weak var courseTime: UILabel!
    
    @IBOutlet weak var courseListBgView: UIView!
    @IBOutlet weak var courseListHeight: NSLayoutConstraint!
    var courseArr = JSON.init(parseJSON: "[]")
    
    func handleGetCourseDetail() {
        var params = JSON.init(parseJSON: "{}")
        params["id"].string = courseId
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.course_detail_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                self.courseData = result["data"]
                self.courseArr = result["data"]["items"]
                self.handleReloadView()
            }
        }
    }
    
    func handleReloadView() {
        let course = courseData["course"]
        courseCover.af.setImage(for: .normal, url: URL(string: course.dictionaryObject!["cover"] as! String)!)
        courseTitle.text = course.dictionaryObject!["name"] as? String
        let desc = course.dictionaryObject!["remark"] as? String
        courseDesc.text = desc == "" ? "暂无" : desc
        courseTime.text = (course.dictionaryObject!["lastModifiedDate"] as? String)!.components(separatedBy: " ")[0]
        
        for view in courseListBgView.subviews {
            view.removeFromSuperview()
        }
        
        let space = 12.0
        let itemHeight = 64.0
        for index in 0..<courseArr.count {
            let item = courseArr[index]
            
            let itemBgView = UIView.init()
            itemBgView.layer.masksToBounds = true
            itemBgView.layer.cornerRadius = 10
            itemBgView.backgroundColor = UIColor.white
            courseListBgView.addSubview(itemBgView)
            if index == 0 {
                itemBgView.snp.makeConstraints { (make) in
                    make.left.top.right.equalToSuperview()
                    make.height.equalTo(itemHeight)
                }
            } else if index == courseArr.count - 1 {
                itemBgView.snp.makeConstraints { (make) in
                    make.left.right.equalToSuperview()
                    make.top.equalTo(courseListBgView.subviews[index - 1].snp.bottom).offset(space)
                    make.bottom.equalToSuperview().offset(-space)
                    make.height.equalTo(courseListBgView.subviews[index - 1].snp.height)
                }
            } else {
                itemBgView.snp.makeConstraints { (make) in
                    make.left.right.equalToSuperview()
                    make.top.equalTo(courseListBgView.subviews[index - 1].snp.bottom).offset(space)
                    make.height.equalTo(courseListBgView.subviews[index - 1].snp.height)
                }
            }
            
            let cover = UIImageView.init()
            if item["remark"].stringValue == "picture" {
                let coverImageUrl = item["path"].stringValue.imageSizeToThumbnail(contentView: cover)
                print("课程列表图片url：\(coverImageUrl)")
                cover.af.setImage(withURL: URL(string: coverImageUrl)!, placeholderImage: UIImage.init(named: "logo"))
            } else {
                cover.image = UIImage(named: remarkToIcon(type: item["remark"].stringValue))
            }
            itemBgView.addSubview(cover)
            cover.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(12)
                make.centerY.equalToSuperview()
                make.width.equalTo(34)
                make.height.equalTo(40)
            }
            
            let title = UILabel.init()
            title.text = item["name"].stringValue
            title.font = UIFont.systemFont(ofSize: 14)
            title.numberOfLines = 2
            title.lineBreakMode = .byTruncatingTail
            title.textAlignment = .left
            title.textColor = AppConfig.sharedInstance.MAIN_TITLE_COLOR
            itemBgView.addSubview(title)
            title.snp.makeConstraints { make in
                make.left.equalTo(cover.snp.right).offset(12)
                make.top.equalToSuperview().offset(12)
                make.right.equalToSuperview().offset(-12)
            }
            
            let btn = UIButton.init()
            btn.setTitle("\(index)", for: .reserved)
            btn.addTarget(self, action: #selector(handleClickCourseware(_:)), for: .touchUpInside)
            itemBgView.addSubview(btn)
            btn.snp.makeConstraints { make in
                make.left.top.bottom.right.equalToSuperview()
            }
            
            if item["remark"].stringValue == "media" ||
                item["remark"].stringValue == "picture" ||
                item["remark"].stringValue == "music" {
                let longPressGesture = LongPressGestureRecognizer.init(target: self, action: #selector(contentItemLongPressGesture(_:)))
                longPressGesture.index = index
                btn.addGestureRecognizer(longPressGesture)
            }
            
        }
        
        if (courseArr.count == 0) {
            let emptyView = EmptyView.init()
            courseListBgView.addSubview(emptyView)
            emptyView.snp.makeConstraints { make in
                make.left.right.top.bottom.equalToSuperview()
                make.height.equalTo(self.view.bounds.width)
            }
        }
        
        courseListHeight.constant = courseArr.count == 0 ? self.view.bounds.width : (space+itemHeight)*Double(courseArr.count)
        
    }
    
    @objc func handleClickCourseware(_ btn: UIButton) {
        let index = Int(btn.title(for: .reserved)!)
        let item = courseArr[index!]
        courseWareTitle = item["name"].stringValue

        if item["remark"].stringValue == "media" ||
            item["remark"].stringValue == "picture" ||
            item["remark"].stringValue == "music" {
            let webView = UtilManager.sharedInstance.getVCFromSB(identifier: "WebViewController") as! WebViewController
            webView.titleStr = courseWareTitle
            webView.url = item["path"].stringValue
            self.navigationController?.pushViewController(webView, animated: true)
        } else if
            item["remark"].stringValue == "docs" ||
            item["remark"].stringValue == "ppt" ||
            item["remark"].stringValue == "pdf" ||
            item["remark"].stringValue == "word" ||
            item["remark"].stringValue == "excel" {
            handleGetSourceKey(id: item["id"].stringValue)
        }
    }
    
    @IBAction func saveCoverImage(_ sender: Any) {
        saveImageToPhotoLibrary(image: courseCover.image(for: .normal))
    }
    
    func handleGetSourceKey(id: String) {
        var params = JSON.init(parseJSON: "{}")
        params["username"].string = UserInfo.sharedInstance.userName
        params["sourceId"].string = id
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.source_key_action, method: HTTPMethod.post, params: params) { (result, error) in
            if error == nil {
                let url = "\(AppConfig.sharedInstance.COURSE_LINK_PREFIX)\(result["data"]["token"].stringValue)&from=pc"
                let webView = UtilManager.sharedInstance.getVCFromSB(identifier: "WebViewController") as! WebViewController
                webView.titleStr = self.courseWareTitle
                webView.url = url
                self.navigationController?.pushViewController(webView, animated: true)
            }
        }
    }
    
    // MARK: 长按课件
    @objc func contentItemLongPressGesture(_ sender: LongPressGestureRecognizer) {
        if sender.state == .began {
            let qrCodeView = QrCodeView.init()
            self.view.addSubview(qrCodeView)
            qrCodeView.snp.makeConstraints { make in
                make.left.right.top.bottom.equalToSuperview()
            }
            
            if let image = EFQRCode.generate(
                for: courseArr[sender.index!].dictionaryObject!["path"] as! String
            ) {
                qrCodeView.img.image = UIImage(cgImage: image)
                print("Create QRCode image success \(image)")
            } else {
                print("Create QRCode image failed!")
            }
        }
    }
    
    func remarkToIcon(type: String) -> String {
        switch type {
        case "docs":
            return "doc"
        case "ppt":
            return "ppt"
        case "pdf":
            return "pdf"
        case "word":
            return "word"
        case "excel":
            return "excel"
        case "media":
            return "media"
        case "picture":
            return "picture"
        case "music":
            return "music"
        default:
            return ""
        }
    }
    
    // MARK: - 保存图片到相册
    func saveImageToPhotoLibrary(image: UIImage?) {
        if let img = image {
            UIImageWriteToSavedPhotosAlbum(img, self, #selector(image(image: didFinishSavingWithErroring: contextInfo:)), nil)
        }
    }
    
    @objc func image(image: UIImage, didFinishSavingWithErroring: NSError?, contextInfo: Any) {
        if didFinishSavingWithErroring != nil {
            self.view.makeToast("保存失败,请打开照片权限", duration: 1.0, position: .center)
            DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                if let url = URL(string: UIApplication.openSettingsURLString) {
                    if UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.open(url, options: [:], completionHandler: nil)
                    }
                }
            }
            
        } else {
            self.view.makeToast("图片保存成功", duration: 1.0, position: .center)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        handleGetCourseDetail()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
